package com.ailk.aee.pcc.dao;

import com.ailk.aee.pcc.mongo.Mongo;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author pengzhang
 */
@Component
public class TargetDao {

    Mongo targetMongo;

    /**
     * 增加用户指标
     *
     * @param targetKey   ?
     * @param channelName ?
     * @param parentKey   ?
     * @param level       ?
     * @param cacheKey    ?
     */
    public BasicDBObject addTarget(
            String targetKey,
            String targetName,
            String channelName,
            String parentKey,
            int level,
            String cacheKey,
            String targetRule,
            String value) {

        BasicDBObject targetObj = new BasicDBObject()
                .append("targetKey", targetKey)
                .append("channelName", channelName)
                .append("parentKey", parentKey)
                .append("targetRule", targetRule)
                .append("targetName", targetName)
                .append("level", level)
                .append("value", value)
                .append("isLeaf", true);

        targetMongo.getContentCollection().update(
                new BasicDBObject("cacheKey", cacheKey),
                new BasicDBObject("$set", targetObj), true, false
        );

        return targetObj;
    }

    /**
     * 父结点
     *
     * @param cacheKey 父缓存结点
     *
     * @return ?
     */
    public DBObject queryTargetByCacheKey(String cacheKey) {
        BasicDBObject query = new BasicDBObject("cacheKey", cacheKey);
        return targetMongo.getContentCollection().findOne(query);
    }


    public DBCursor queryTargetListByParentCache(String channelName, String parentKey, int start, int limit) {
        BasicDBObject query = new BasicDBObject("parentKey", parentKey).append("channelName", channelName);
        return targetMongo.getContentCollection().find(query).skip(start).limit(start + limit);
    }

    public DBCursor queryTargetListByParentCache(String channelName, String parentKey) {
        BasicDBObject query = new BasicDBObject("parentKey", parentKey).append("channelName", channelName);
        return targetMongo.getContentCollection().find(query, new BasicDBObject("cacheKey", 1));
    }

    public void deleteTarget(String cacheKey) {
        BasicDBObject query = new BasicDBObject("cacheKey", cacheKey);
        targetMongo.getContentCollection().remove(query);
    }

    public void updateLeaf(String cacheKey, boolean isLeaf) {
        BasicDBObject query = new BasicDBObject("cacheKey", cacheKey);
        BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("isLeaf", isLeaf));
        targetMongo.getContentCollection().update(query, update, true, false);

    }

}
